import Phaser from 'phaser'

export default class MatchingScene extends Phaser.Scene {
  constructor() {
    super({ key: 'MatchingScene' })
    this.englishWords = ['apple', 'book', 'cat', 'dog', 'elephant',
      'flower', 'guitar', 'house', 'ice cream', 'jacket']
    this.chineseWords = ['苹果', '书', '猫', '狗', '大象',
      '花', '吉他', '房子', '冰淇淋', '夹克']
    this.correctPairs = new Map([
      ['apple', '苹果'], ['book', '书'], ['cat', '猫'],
      ['dog', '狗'], ['elephant', '大象'], ['flower', '花'],
      ['guitar', '吉他'], ['house', '房子'],
      ['ice cream', '冰淇淋'], ['jacket', '夹克']
    ])
  }

  create() {
    // 创建图层
    this.backgroundLayer = this.add.container(0, 0);
    this.connectionLayer = this.add.container(0, 0);
    this.contentLayer = this.add.container(0, 0);

    // 将图形添加到连线层
    this.graphics = this.add.graphics()
    this.connectionLayer.add(this.graphics);

    // 初始化状态
    this.selectedEnglish = null
    this.selectedChinese = null
    this.connections = []
    this.englishTexts = []
    this.chineseTexts = []

    this.createWords()

    // 添加窗口大小变化监听
    this.scale.on('resize', this.handleResize, this);
    
    // 初始化布局
    this.handleResize(this.scale.gameSize);
  }

  handleResize(gameSize) {
    const width = gameSize.width;
    const height = gameSize.height;
    const isLandscape = width > height;
    const isMobile = width < 768;
    const dpr = window.devicePixelRatio || 1;
    
    // 移动端横屏时使用上下布局
    const useVerticalLayout = isMobile && isLandscape;
    
    // 计算响应式尺寸
    const padding = isMobile ? width * 0.04 : Math.min(width * 0.05, 40);
    const columnWidth = useVerticalLayout 
      ? width * 0.8 
      : (isMobile ? width * 0.4 : Math.min(width * 0.3, 200));
    const startY = height * 0.1;
    const fontSize = Math.max(Math.min(width * 0.025, 18), 14);

    // 计算布局
    let englishX, chineseX, englishStartY, chineseStartY;
    if (useVerticalLayout) {
      // 上下布局
      englishX = (width - columnWidth) / 2;
      chineseX = englishX;
      englishStartY = startY;
      chineseStartY = startY + (this.englishWords.length * 60) + 40; // 添加一些间距
    } else {
      // 左右布局
      const contentWidth = columnWidth * 2 + padding * 2;
      const leftOffset = (width - contentWidth) / 2;
      englishX = leftOffset;
      chineseX = leftOffset + contentWidth - columnWidth;
      englishStartY = startY;
      chineseStartY = startY;
    }

    // 计算单词之间的间距
    const itemHeight = Math.min(50, useVerticalLayout ? 45 : 40);
    const spacing = itemHeight * 1.2;

    // 更新英文单词位置
    this.englishTexts.forEach((button, index) => {
      button.setPosition(englishX, englishStartY + index * spacing);
      const bg = button.first;
      const text = button.last;
      bg.setSize(columnWidth, itemHeight * 0.9);
      text.setFontSize(fontSize)
        .setWordWrapWidth(columnWidth * 0.95)
        .setResolution(dpr * 2);
    });

    // 更新中文单词位置
    this.chineseTexts.forEach((button, index) => {
      button.setPosition(chineseX, chineseStartY + index * spacing);
      const bg = button.first;
      const text = button.last;
      bg.setSize(columnWidth, itemHeight * 0.9);
      text.setFontSize(fontSize)
        .setWordWrapWidth(columnWidth * 0.95)
        .setResolution(dpr * 2);
    });

    // 调整场景大小以适应内容
    if (useVerticalLayout) {
      const totalHeight = chineseStartY + (this.chineseWords.length * spacing) + padding;
      this.scale.resize(width, Math.max(height, totalHeight));
    }

    // 重绘连线
    this.drawConnections();
  }

  createWords() {
    const width = this.scale.width;
    const isMobile = width < 768;
    const padding = isMobile ? width * 0.03 : Math.min(width * 0.04, 30);
    const columnWidth = isMobile ? width * 0.44 : Math.min(width * 0.35, 280);
    const contentWidth = columnWidth * 2 + padding * 2;
    const leftOffset = (width - contentWidth) / 2;
    const startY = this.scale.height * 0.15;
    const itemHeight = 45;

    // 计算列的水平位置
    const englishX = leftOffset;
    const chineseX = leftOffset + contentWidth - columnWidth;

    // 打乱中文单词顺序
    const shuffledChinese = [...this.chineseWords]
      .map(value => ({ value, sort: Math.random() }))
      .sort((a, b) => a.sort - b.sort)
      .map(({ value }) => value);

    // 创建英文单词
    this.englishWords.forEach((word, index) => {
      const y = startY + index * itemHeight;
      const button = this.createWordButton(word, englishX, y, columnWidth, 'eng');
      this.englishTexts.push(button);
    });

    // 创建中文单词
    shuffledChinese.forEach((word, index) => {
      const y = startY + index * itemHeight;
      const button = this.createWordButton(word, chineseX, y, columnWidth, 'chn');
      this.chineseTexts.push(button);
    });
  }

  createWordButton(word, x, y, width, type) {
    const button = this.add.container(x, y);
    const height = Math.min(this.scale.height * 0.075, 45) * 0.9;
    const dpr = window.devicePixelRatio || 1;
    
    // 创建背景
    const bg = this.add.rectangle(0, 0, width, height, 0xffffff)
      .setOrigin(0)
      .setInteractive()
      .setStrokeStyle(2, 0xe0e0e0); // 添加边框
    
    // 创建文本
    const text = this.add.text(width/2, height/2, word, {
      fontSize: Math.max(Math.min(this.scale.width * 0.025, 18), 14),
      fill: '#2c3e50',
      fontFamily: 'Arial',
      resolution: dpr * 2,
      align: 'center',
      wordWrap: { width: width * 0.95 }
    }).setOrigin(0.5);

    button.add([bg, text]);
    this.contentLayer.add(button);

    // 添加交互
    bg.on('pointerover', () => {
      bg.setFillStyle(0xf0f9ff) // 更明显的悬停颜色
    })
    bg.on('pointerout', () => {
      if ((type === 'eng' && this.selectedEnglish !== button) ||
          (type === 'chn' && this.selectedChinese !== button)) {
        bg.setFillStyle(0xffffff)
      }
    })
    bg.on('pointerdown', () => {
      this.selectWord(button, word, type)
    })

    return button
  }

  selectWord(button, word, type) {
    if (type === 'eng') {
      // 如果点击已选中的按钮，取消选择
      if (this.selectedEnglish === button) {
        this.selectedEnglish.first.setFillStyle(0xffffff).setStrokeStyle(2, 0xe0e0e0)
        this.selectedEnglish = null
        return
      }
      if (this.selectedEnglish) {
        this.selectedEnglish.first.setFillStyle(0xffffff).setStrokeStyle(2, 0xe0e0e0)
      }
      this.selectedEnglish = button
      button.first.setFillStyle(0xe3f2fd).setStrokeStyle(2, 0x2196f3)
    } else {
      // 如果点击已选中的按钮，取消选择
      if (this.selectedChinese === button) {
        this.selectedChinese.first.setFillStyle(0xffffff).setStrokeStyle(2, 0xe0e0e0)
        this.selectedChinese = null
        return
      }
      if (this.selectedChinese) {
        this.selectedChinese.first.setFillStyle(0xffffff).setStrokeStyle(2, 0xe0e0e0)
      }
      this.selectedChinese = button
      button.first.setFillStyle(0xe3f2fd).setStrokeStyle(2, 0x2196f3)
    }

    this.tryConnect(word)
  }

  tryConnect(word) {
    if (this.selectedEnglish && this.selectedChinese) {
      const engWord = this.selectedEnglish.last.text
      const chnWord = this.selectedChinese.last.text

      // 检查是否已经存在这些单词的连线
      const existingEngConnection = this.connections.find(conn => conn.eng === engWord)
      const existingChnConnection = this.connections.find(conn => conn.chn === chnWord)

      // 如果存在旧连线，删除它们
      if (existingEngConnection || existingChnConnection) {
        this.connections = this.connections.filter(conn => 
          conn.eng !== engWord && 
          conn.eng !== existingChnConnection?.eng &&
          conn.chn !== chnWord &&
          conn.chn !== existingEngConnection?.chn
        )

        // 重置之前连接的按钮样式
        this.englishTexts.forEach(button => {
          if (button.last.text === existingEngConnection?.eng || 
              button.last.text === existingChnConnection?.eng) {
            button.first.setFillStyle(0xffffff).setStrokeStyle(2, 0xe0e0e0)
          }
        })
        this.chineseTexts.forEach(button => {
          if (button.last.text === existingEngConnection?.chn || 
              button.last.text === existingChnConnection?.chn) {
            button.first.setFillStyle(0xffffff).setStrokeStyle(2, 0xe0e0e0)
          }
        })
      }

      // 添加新连线
      this.connections.push({ eng: engWord, chn: chnWord })

      // 重绘所有连线
      this.drawConnections()

      // 保持当前选中状态的视觉效果
      this.selectedEnglish.first.setFillStyle(0xe3f2fd).setStrokeStyle(2, 0x2196f3)
      this.selectedChinese.first.setFillStyle(0xe3f2fd).setStrokeStyle(2, 0x2196f3)

      // 不重置选中状态，允许继续连线
      // this.selectedEnglish = null
      // this.selectedChinese = null

      console.log('Current connections:', this.connections)
    }
  }

  drawConnections() {
    this.graphics.clear();
    this.graphics.lineStyle(4, 0x2196f3, 0.9); // 保持粗线条

    this.connections.forEach(({ eng, chn }) => {
      const engButton = this.englishTexts.find(t => t.last.text === eng);
      const chnButton = this.chineseTexts.find(t => t.last.text === chn);

      if (engButton && chnButton) {
        const startX = engButton.x + engButton.first.width;
        const startY = engButton.y + engButton.first.height / 2;
        const endX = chnButton.x;
        const endY = chnButton.y + chnButton.first.height / 2;

        // 使用直线连接
        this.graphics
          .beginPath()
          .moveTo(startX, startY)
          .lineTo(endX, endY)
          .strokePath();
      }
    });
  }

  checkAnswers() {
    this.graphics.clear()
    let score = 0

    this.connections.forEach(({ eng, chn }) => {
      const engButton = this.englishTexts.find(
        t => t.last.text === eng
      )
      const chnButton = this.chineseTexts.find(
        t => t.last.text === chn
      )

      if (engButton && chnButton) {
        const isCorrect = this.correctPairs.get(eng) === chn
        if (isCorrect) score++

        const color = isCorrect ? 0x4caf50 : 0xf44336
        this.graphics.lineStyle(4, color, 1)
        
        const startX = engButton.x + engButton.first.width
        const startY = engButton.y + engButton.first.height / 2
        const endX = chnButton.x
        const endY = chnButton.y + chnButton.first.height / 2
        
        // 使用直线连接
        this.graphics
          .beginPath()
          .moveTo(startX, startY)
          .lineTo(endX, endY)
          .strokePath()

        // 添加对错标记
        const midX = (startX + endX) / 2
        const midY = (startY + endY) / 2
        this.drawMark(midX, midY, isCorrect)
      }
    })

    // 显示得分
    const dpr = window.devicePixelRatio || 1;
    const scoreText = this.add.text(
      this.scale.width / 2,
      this.scale.height * 0.95,
      `得分: ${score}/${this.englishWords.length}`,
      {
        fontSize: Math.max(Math.min(this.scale.width * 0.03, 24), 16),
        fill: '#2c3e50',
        fontFamily: 'Arial',
        resolution: dpr * 2
      }
    ).setOrigin(0.5);
  }

  drawMark(x, y, isCorrect) {
    const circle = this.add.circle(x, y, 12, isCorrect ? 0x4caf50 : 0xf44336)
    this.add.text(x, y, isCorrect ? '✓' : '✕', {
      fontSize: '16px',
      fill: '#ffffff',
      fontFamily: 'Arial'
    }).setOrigin(0.5)
  }
} 